<template>
  <div>
    <el-table
      v-bind="$attrs"
      v-on="$listeners"
      ref="tableRef"
      :max-height="maxHeightVal"
      :data="getData()"
      :row-style="rowStyle"
      :cell-style="handCellStyle"
      :span-method="arraySpanMethod"
      size="small"
      :stripe="stripe"
      :tooltip-effect="tooltipEffect"
      highlight-current-row
      @selection-change="handleSelectionChange"
      @expand-change="expandChange"
      @sort-change="sortChange"
      @select="select"
      @select-all="selectall"
      @row-click="rowClick"
      @cell-dblclick="clickCopy"
    >
      <el-table-column v-if="selection" type="selection" :fixed="selectFixed" width="45" />
      <el-table-column
        v-if="order"
        label="序号"
        :index="indexMethod"
        :fixed="orderFixed"
        type="index"
        width="75"
        align="center"
        :key="okey"
      />
      <!-- table内容 -->
      <slot></slot>
    </el-table>
    <div v-if="pagination" class="edu-pagination">
      <div v-if="paginationShowRefresh" class="float-right">
        <el-button
          type="text"
          class="el-icon-refresh"
          @click="refreshBtnClick"
        />
      </div>
      <div class="float-right">
        <el-pagination
          :current-page.sync="cPageNum"
          :page-sizes="pageSizes ? pageSizes : [10, 20, 50, 100, 500, 1000]"
          :page-size="cPageSize"
          :total="getTotal()"
          :layout="paginationLayout"
          :small="paginationSmall"
          @keyup.enter.native="handleKey"
          @current-change="onCurrentPageChange"
          @size-change="onPageSizeChange"
          @keyup.enter.native.self.stop="
            e => {
              onCurrentPageChange(e.target.value);
            }
          "
        />
      </div>
    </div>
  </div>
</template>
<script>
// import fetch from "@/utils/fetch";
import request from '@/api/request.js';
// import UTILS from "@/utils/utils";
import { TableColumn } from 'element-ui'
/**
 * 表格组件
 */
export default {
  name: "edu-table",
  props: {
    maxHeight: {
      type: Number,
      // default: 450
    },
    orderFixed: {
      // 序号是否固定
      type: Boolean,
      default: false
    },
    selectFixed: {
      // 复选框是否固定
      type: Boolean,
      default: false
    },
    selection: {
      // 是否多选
      type: Boolean,
      default: true
    },
    order: {
      // 是否加上序号
      type: Boolean,
      default: true
    },
    okey:{
      type: Number,
      default: Math.random()
    },
    pagination: {
      // 是否使用分页
      type: Boolean,
      default: true
    },
    data: {
      type: Array,
      default: () => []
    },
    rowStyle: {
      default: () => {
        20;
      }
    },
    total: {
      // 总数
      type: Number,
      default: 0
    },
    pageNum: {
      // 当前页码
      type: Number,
      default: 1
    },
    pageSize: {
      // 每页显示数
      type: Number,
      default: 20
    },
    url: {
      type: String,
      default: null
    },
    merge: {
      type: Boolean,
      default: false
    },
    defaultIndex: {
      type: Boolean,
      default: false
    },
    cellSpan: {
      type: Object,
      default: null
    },
    paginationLayout: {
      // default: "total, prev, pager, next, jumper"
      default: "total, sizes, prev, pager, next, jumper"
    },
    paginationSmall: {
      default: false
    },
    paginationShowRefresh: {
      default: false
    },
    cellBackgroundColor: {
      type: String,
      default: null
    },
    pageSizes: {
      type: Array,
      default: null
    },
    tooltipEffect: {
      type: String,
      default: "light"
    },
    stripe: {
      type: Boolean,
      default: true
    },
    isRowClickChangeRowSelection: {
      // 点击行是否出发复选框选中事件
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      dataList: [],
      total_: 0,
      condition: null,
      selectionDatas: null,
      maxHeightVal:null,
      cPageNum:this.pageNum,
      cPageSize:this.pageSize,
    };
  },
  watch: {
    pageNum(newValue, oldValue) {
      this.cPageNum = newValue
    },
    pageSize(newValue, oldValue) {
      this.cPageSize = newValue
    }
  },
  beforeCreate () {
    // console.log(TableColumn.props);
    // 全局字段支持排序 但无法过滤操作 和 选择框
    TableColumn.props.sortable = {default:true,type:Boolean}
    TableColumn.props.formatter = {
      type:Function,
      default:function(row, column, cellValue, index){
        // console.log(cellValue);
        // console.log(index);
        if(cellValue === null || cellValue === '' || cellValue === undefined){
          return '--'
        }else{
          return cellValue
        }
      }
    }
  },
  mounted () {
    // 指定字段支持排序
    // this.$refs.tableRef.sort('studentId', 'descending')
    // console.log(this.$refs.tableRef.columns);
    this.$refs.tableRef.columns.map((e)=>{
      // console.log(e);
      if(e.label == '操作' || e.type == 'selection'){
        e.sortable = false
      }else{
        e.sortable = true
      }
    })

    setTimeout(() => {
      this.setMaxHeight()
    }, 1000);
  },
  // watch: {
  //   data(newValue, oldValue) {
  //     // console.log('newValue');
  //     console.log(newValue == oldValue);
  //     // console.log(newValue);
  //     this.setMaxHeight()
  //   }
  // },
  methods: {
    // 点击复制单元格内容
    clickCopy(row,field,cell,event){
      // console.log(row);
      // console.log(field);
      // console.log(cell);
      // console.log(event);
      // console.log(event.target);

      let target = event.target
      let classNames = target.getAttribute("class")
      let width = target.offsetWidth - 20 //padding距离

      // 创建临时dom用来获取文字真实宽度
      let TemporaryTag = document.createElement('span');
      TemporaryTag.innerText = row[field.property];
      TemporaryTag.className = 'tempTextWidth';
      document.querySelector('body').appendChild(TemporaryTag);
      let tempTextWidth = document.querySelector('.tempTextWidth').offsetWidth;
      document.querySelector('.tempTextWidth').remove();

        // console.log(width);
        // console.log(tempTextWidth);
        // console.log(tempTextWidth > width);

      if(tempTextWidth > width){
        let val = row[field.property]

        if(val){
          let input = document.createElement('input')
          input.setAttribute('readonly','readonly')
          input.value = val
          document.body.appendChild(input)
          input.select()
          document.execCommand("copy")
          document.body.removeChild(input)

          this.$notify({
            title: '成功',
            message: '内容已复制成功,ctrl+v粘贴',
            type:'success'
          });
        }
      }
      
    },
    setMaxHeight(){
      // 外部设置的固定值
      if(this.maxHeight) {
        this.maxHeightVal = this.maxHeight
      }

      // 计算高度
      // 筛选条件高度
      let filterForm = document.getElementsByClassName('conditionFilter')
      let filterFormHeight = (filterForm.length>0 && filterForm[0].offsetHeight) || 0
      // el-card.desc
      let cardDesc = document.querySelectorAll('.el-card.desc')
      let cardDescFormHeight = (cardDesc.length>0 && (cardDesc[0].offsetHeight + 10)) || 0
      // cardMiniBar
      let cardMiniBar = document.querySelectorAll('.cardMiniBar')
      let cardMiniBarFormHeight = (cardMiniBar.length>0 && (cardMiniBar[0].offsetHeight + 10)) || 0
      // console.log(cardDescFormHeight);
      // console.log(cardMiniBarFormHeight);
      // 标题高度
      let conditionTitle = document.getElementsByClassName('condition-title')
      let conditionTitleHeight = conditionTitle.length>0 && conditionTitle[0].offsetHeight
      let bodyHeight = document.body.offsetHeight - 35 - 64 - (10*2) - filterFormHeight - cardDescFormHeight - cardMiniBarFormHeight -(15*2) - conditionTitleHeight - 50
      // console.log(filterForm);
      // console.log(filterFormHeight);
      // console.log(conditionTitle);
      // console.log(conditionTitleHeight);
      let height = bodyHeight < 400 ? 400 : bodyHeight
      // console.log('height'+height);
      // console.log('bodyHeight'+bodyHeight);
      this.maxHeightVal = height
      // this.maxHeightVal = bodyHeight
    },
    indexMethod(index) {
      if (this.defaultIndex) return index;
      else return (this.cPageNum - 1) * this.cPageSize + index + 1;
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      // 合并行
      if (this.cellSpan) {
        for (let key in this.cellSpan) {
          if (column.property == key) {
            const _row = this.cellSpan[key][rowIndex];
            const _col = _row > 0 ? 1 : 0;
            return {
              rowspan: _row,
              colspan: _col
            };
          }
        }
      }
      if (!this.merge) return;
      let { columnList } = row;
      if (!columnList) return;
      let mergeData = columnList.filter(el => {
        return el.index === columnIndex;
      });
      if (mergeData.length === 1) {
        let { index, rowspan, colspan } = mergeData[0];
        if (index === columnIndex) {
          return {
            rowspan,
            colspan
          };
        }
      }
    },
    getData() {
      if (this.url) {
        return this.dataList;
      }
      return this.data;
    },
    getTotal() {
      if (this.url) {
        return this.total_;
      }
      return this.total;
    },
    handleSelectionChange(val) {
      this.selectionDatas = val;
      this.$emit("selection-change", val);
    },
    // 设置cell背景颜色，根据子组件传参cellBackgroundColor cell颜色，cellFillingList 在row中传递要填充的数组
    handCellStyle({ row, column, rowIndex, columnIndex }) {
      if (this.cellBackgroundColor && row.cellFillingList) {
        let tempCellFillingList = row.cellFillingList;
        if (tempCellFillingList.includes(columnIndex)) {
          return this.cellBackgroundColor;
        }
      } else {
        return null;
      }
    },
    onPageSizeChange(size) {
      this.cPageSize = size;
      // 当前页展示列表数量(pageSize)发生变化时默认将请求的页数设置为1
      this.cPageNum = 1;
      this.pageChange();
    },
    onCurrentPageChange(currentPage) {
      this.cPageNum = currentPage;
      this.pageChange();
    },
    pageChange() {
      if (this.url) {
        this.search(this.condition);
      }

      this.$emit("page-change", {
        pageSize: this.cPageSize,
        pageNum: this.cPageNum
      });
    },
    getCheckData(key) {
      let result = [];
      if (!_.isEmpty(this.selectionDatas)) {
        if (key) {
          for (const data of this.selectionDatas) {
            result.push(data[key]);
          }
        } else {
          result = this.selectionDatas;
        }
      }
      return result;
    },
    clearSelection() {
      this.$refs.tableRef && this.$refs.tableRef.clearSelection();
    },
    clearTable() {
      this.clearSelection();
      this.dataList = [];
      this.total_ = 0;
    },
    search(data) {
      this.condition = data;
      let param = {
        pageNum_: this.cPageNum,
        pageSize_: this.cPageSize,
        condition: data
      };
      if (!this.pagination) {
        param = data;
      }
      return request({
        url: this.url,
        method: "post",
        data: param
      })
        .then(res => {
          if (!_.isNil(res.data)) {
            this.dataList = res.data.list;
            this.total_ =
              res.data.total_ == null ? res.data.total : res.data.total_;
            this.$emit("load-done", this.dataList);
          } else {
            this.dataList = [];
            this.total_ = 0;
          }
          return res;
        })
        .catch(error => {
          this.dataList = [];
          this.total_ = 0;
        });
    },
    sortChange(column,prop,order) {
      this.$emit("sort-change",column,prop,order,this.dataList);
    },
    refreshDirectNameData(dataList) {
      this.dataList = dataList
    },
    expandChange(row, expandedRows) {
      this.$emit("expandChange", row, expandedRows);
    },
    select(selection, row) {
      this.$emit("select", selection, row);
    },
    selectall(selection) {
      this.$emit("select-all", selection);
    },
    handleKey(e) {
      if (e.target.validity.badInput) {
        this.$message({
            type: 'error',
            message: '请输入正确的页数'
        })
        return
      }
      e.target.blur()
      this.onCurrentPageChange(e.target.value)
    },
    refreshBtnClick() {
      if (this.url) {
        this.search(this.condition);
      }
      this.$emit("refresh-click");
    },
    rowClick(row, column, event) {
      this.toggleRowSelection(row);
      this.$emit("rowClick",row);
    },
    toggleRowSelection(row, flag) {
      this.isRowClickChangeRowSelection && this.$refs.tableRef.toggleRowSelection(row, flag);
    },
    resetPageNum(data) {
      if (data) {
        this.condition = data;
      }
      this.cPageNum = 1;
      if (this.url) {
        this.search(this.condition);
      }
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep.el-table{
  .el-table__empty-block{
    width: 100%!important;
    border-bottom: 1px solid #ebeef5;
  }
}

</style>
